import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Button, Popconfirm } from 'antd';
import React, { useRef, useState } from 'react';
import { useModel } from 'umi';
import Form from './components/Form';

// import * as c from '@/services/consts';
import * as api from '@/services/ticketType';
import { PageContainer } from '@ant-design/pro-components';

const VpnGroupTreeList: React.FC = () => {
  const [formVisible, setFormVisible] = useState<boolean>(false);
  const [current, setCurrent] = useState<API.TicketType | undefined>(undefined);
  const [parent, setParent] = useState<API.TicketType | undefined>(undefined);

  const actionRef = useRef<ActionType>();

  const { hasRight } = useModel('useAuthModel');

  const { getProduct, reloadTicketTypeTrees } = useModel(
    'useGlobalModel',
    (model) => ({
      getProduct: model.getProduct,
      reloadTicketTypeTrees: model.reloadTicketTypeTrees,
    }),
  );

  const loadData = async (
    params: { [key: string]: any },
    sorter?: { [key: string]: any },
    filter?: { [key: string]: any },
  ) => {
    const result = await api.list(params, sorter, filter);

    //console.log(result);
    return Promise.resolve(result);
  };

  const handleFormSubmit = async (record: API.TicketType) => {
    if (parent) {
      record.parentId = parent.id;
    }

    // console.log(record);

    let result: API.Result;
    if (current) {
      result = await api.update({
        ...current,
        ...record,
      });
    } else {
      result = await api.add({ ...record });
    }

    if (result && result.success === true) {
      setCurrent(undefined);
      setFormVisible(false);
      setParent(undefined);
      actionRef.current?.reload();

      //更新缓存
      await reloadTicketTypeTrees();
    }
  };

  const handleRemove = async (id: number) => {
    const result = await api.remove({ key: id });
    if (result.success) {
      actionRef.current?.reload();

      //更新缓存
      await reloadTicketTypeTrees();
    }
  };

  let columns: ProColumns<API.TicketType>[] = [
    {
      title: '产品',
      align: 'center',
      width: 200,
      dataIndex: 'productIdsText',
      sorter: true,
      renderText: (_, record) => {
        if (record.productId) {
          let text = '';
          const product = getProduct(record.productId);
          if (product) {
            if (text != '') {
              text += '/';
            }
            text += product.name;
          }
          return text;
        }
        return '';
      },
    },
    {
      title: '名称',
      dataIndex: 'name',
      sorter: true,
    },
    {
      title: '排序',
      dataIndex: 'sort',
      width: 100,
      sorter: true,
    },
    {
      title: '备注',
      dataIndex: 'remark',
      valueType: 'textarea',
      ellipsis: true,
    },
  ];

  columns = columns.concat([
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      width: 180,
      render: (_, record) => {
        let cmps = [];
        if (hasRight('tickettype_update')) {
          cmps.push(
            <a
              key="edit"
              onClick={(e) => {
                setFormVisible(true);
                setCurrent(record);
                setParent(undefined);
              }}
            >
              编辑
            </a>,
          );
        }
        if (hasRight('tickettype_delete')) {
          cmps.push(
            <Popconfirm
              key="delete"
              title="确定要删除吗?"
              onConfirm={async () => {
                await handleRemove(record.id);
              }}
            >
              <a>删除</a>
            </Popconfirm>,
          );
        }

        if (!record.parentId && hasRight('tickettype_create')) {
          cmps.push(
            <a
              key="create"
              onClick={(e) => {
                setFormVisible(true);
                setCurrent(undefined);
                setParent(record);
              }}
            >
              新建子分类
            </a>,
          );
        }

        return cmps;
      },
    },
  ]);

  return (
    <PageContainer>
      <ProTable
        rowKey="id"
        actionRef={actionRef}
        options={{
          fullScreen: false,
          reload: true,
          setting: false,
          density: false,
        }}
        search={false}
        pagination={false}
        toolBarRender={() => {
          if (hasRight('tickettype_create')) {
            return [
              <Button
                type="primary"
                key="create"
                onClick={() => {
                  setFormVisible(true);
                }}
              >
                <PlusOutlined /> 新建
              </Button>,
            ];
          }
          return [];
        }}
        columns={columns}
        request={loadData}
      />
      <Form
        visible={formVisible}
        current={current}
        parent={parent}
        onSubmit={handleFormSubmit}
        onCancel={() => {
          setFormVisible(false);
          setCurrent(undefined);
        }}
      />
    </PageContainer>
  );
};

export default VpnGroupTreeList;
